package com.sgb.capital.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.model.Bean;
import com.sgb.capital.view.widget.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/**
 * 作者: zhangl
 * 时间: 2017/11/2 0002
 * 描述: UI工具类
 **/

public class Utils {
    /**
     * 全局的上下文
     */
    private static Context mBaseContext;
    private static Handler mHandler;
    private static PopupWindow mPopupWindow;

    public static Context getContext() {
        return mBaseContext;
    }

    public static void init(Context application) {
        mBaseContext = application;
        mHandler = new Handler();
    }

    /**
     * 提交一个任务
     */
    public static void post(Runnable task) {
        mHandler.post(task);
    }

    /**
     * 延时提交一个任务
     */
    public static void postDelay(Runnable task, long delay) {
        mHandler.postDelayed(task, delay);
    }

    /**
     * 取消一个任务
     */
    public static void cacel(Runnable task) {
        mHandler.removeCallbacks(task);
    }

    public static String[] getStringArray(int resId) {
        return mBaseContext.getResources().getStringArray(resId);
    }

    // 获取资源文件夹
    public static Resources getResources() {
        return mBaseContext.getResources();
    }

    // 获取资源文件夹的字符串
    public static String getString(int id, Object... formatArgs) {
        return getResources().getString(id, formatArgs);
    }


    public static String getDateHHmm(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String getTime(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String get2Time(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static int getScreenHeight(Activity activity) {
        return activity.getWindowManager()
                .getDefaultDisplay().getHeight();
    }

    public static int getScreenWidth(Activity activity) {
        return activity.getWindowManager()
                .getDefaultDisplay().getWidth();
    }

    public static void getPwdStyle(CharSequence s, int start, int before, EditText editText) {
        if (s == null || s.length() == 0) return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                    sb.insert(sb.length() - 1, ' ');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == ' ') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            editText.setText(sb.toString());
            editText.setSelection(index);
        }
    }

    /**
     * dp --> px
     *
     * @param dp
     * @return
     */
    public static float dp2px(float dp) {
        float dimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,
                dp,
                getResources().getDisplayMetrics());
        return dimension;
    }

    // 将px转换为dp
    public static float px2dp(float px) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                px,
                getResources().getDisplayMetrics());
    }


    public static int getColor(int colorId) {
        return getResources().getColor(colorId);
    }


    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap, String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {
            baos.reset();
            options -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            long length = baos.toByteArray().length;
        }
        //  File file = new File(Constants.CAPTURED_FRAME_FILE_PATH + path);
        try {
            //   FileOutputStream fos = new FileOutputStream(file);
            FileOutputStream fos = new FileOutputStream(new File(""));
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {

                System.out.println("异常信息1==" + e.toString());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            System.out.println("异常信息2==" + e.toString());
            e.printStackTrace();
        }
        //return file;
        return null;
    }


    public static void destroyBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        if (!bitmap.isRecycled())
            bitmap.recycle();
        bitmap = null;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    public static void deleteFiles(File file) {
        if (file != null && file.exists() && file.isDirectory()) {
            for (File item : file.listFiles()) {
                item.delete();
            }
        }
    }


    //将bitmap调整到指定大小
    public static Bitmap sizeBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (!origin.isRecycled()) {//这时候origin还有吗？
            origin.recycle();
        }
        return newBM;
    }

    /**
     * 手机号码的格式183-2964-611
     *
     * @param s
     * @param start
     * @param before
     * @param et_01
     */
    private static void getPhoneStyle(CharSequence s, int start, int before, EditText et_01) {
        if (s == null || s.length() == 0) return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == '-') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != '-') {
                    sb.insert(sb.length() - 1, '-');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == '-') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            et_01.setText(sb.toString());
            et_01.setSelection(index);
        }
    }

    /**
     * 车牌验证
     *
     * @param plate
     * @return
     */
    public static boolean isPlateLogistics(String plate) {
        String commonPlatePattern =  "^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$";
        return plate.matches(commonPlatePattern);
    }

    /**
     * 车牌验证
     *
     * @param plate
     * @return
     */
    public static boolean isPlate(String plate) {
        boolean flag = isCommonPlate(plate) || isNewEnergyVehiclePlate(plate) || isCivilSpecialPlate(plate) || isWJPlate(plate) || isMilitaryVehiclePlate(plate);
        return flag;
    }

    /**
     * <pre>
     * 普通车牌（蓝牌、黄牌）
     * 车牌号码长度：7 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 省份简称    发证机关代码 号码 号码 号码 号码 号码
     * 省份简称：
     * 京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新
     * 发证机关代码：
     * ABCDEFGHxJKLMNxPQRSTUVWXYx
     * 说明：无 I, O , Z 三个字母。其中O和Z属于特殊车牌类型，见其它类型说明。
     * 车牌号码：
     * 数字：0123456789
     * 字母：ABCDEFGHxJKLNMxPQRSTUVWXY
     *
     * 说明：无 I, O 字母；
     * </pre>
     * 普通车牌
     *
     * @param plate
     * @return
     */
    public static boolean isCommonPlate(String plate) {
        String commonPlatePattern = "^([京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\\dABCDEFGHJKLNMPQRSTUVWXYZ]{5})$";
        return plate.matches(commonPlatePattern);
    }

    /**
     * 新能源车牌
     * <pre>
     * 车牌号码长度：8 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位    第8位
     * 省份  发证机关   号码 号码 号码 号码 号码 号码
     * 新能源车牌现阶段号码长度为8位，按照现行新能源车牌号码规则：
     * 第3位：1-9DF
     * 第4位：1-9A-Z，无I、O字母；
     * 第5-7位：0-9
     * 第8位：1-9DF
     * 严格校验新能源车牌号码的约束规则：
     * 当第3位为D/F时，第4位可字母和数字，第5-8位必须纯数字；
     * 当第8位为D/F时，第3-7位必须纯数字；
     * </pre>
     *
     * @param plate
     * @return
     */
    public static boolean isNewEnergyVehiclePlate(String plate) {
        String nevPattern = "^([京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][1-9][1-9ABCDEFGHJKLMNPQRSTUVWXYZ]\\d{4}|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][DF][0-9ABCDEFGHJKLMNPQRSTUVWXYZ]\\d{5}|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY]\\d{5}[DF])$";
        return plate.matches(nevPattern);
    }

    /**
     * 民用特殊Civil special车牌
     * <pre>
     *  港澳车牌
     * 车牌号码长度：7 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 粤   Z  号码 号码 号码 号码 [港澳]
     * 第1、2位分别是“粤Z”，第7位为“港澳”。
     *
     *
     * 教练车 - 学
     * 教练车号牌的第7位固定为“学”字，其它号码与普通民用车牌一致；
     *
     * 拖挂车 - 挂
     * 拖挂车的车厢，其号牌的第7位固定为“挂”字，其它号码与普通民用车牌一致；
     *
     * 其它可能出现的字符：领试超练
     * 其号牌的第7位固定为“领试超练”某个字，其它号码与普通民用车牌一致；
     *
     * 民航内部车牌
     * 车牌号码长度：7 位
     *
     * 车牌号码格式：
     *
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 民   航  号码 号码 号码 号码 号码
     * 使馆车牌
     * 车牌号码长度：7 位
     *
     * 新式使馆车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * [1-3]   数字 数字 号码 号码 号码 使
     * 旧式使馆车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 使   [1-3]  数字 数字 号码 号码 号码
     *  </pre>
     *
     * @param plate
     * @return
     */
    public static boolean isCivilSpecialPlate(String plate) {
        String csPattern = "^([粤][Z][0-9ABCDEFGHJKLMNPQRSTUVWXYZ]\\d{4}[港澳]|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{4}[学挂领试超练]|[民][航][\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{5}|[1-3]\\d{2}[\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{3}[使]|[使][1-3]\\d{2}[\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{3})$";
        return plate.matches(csPattern);
    }

    /**
     * 武警车牌 2012式车牌规则
     * <pre>
     * 警队车牌规则
     * 警队车牌包括四种车牌：
     *
     * 地方武警车牌；
     * 武警总队车牌；
     * 普通警察车牌；
     * O字警察车牌；
     *
     * 地方武警车牌
     * 车牌号码长度：8 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位    第8位
     * W   J  省份简称   号码 号码 号码 号码 号码
     * 其中号码字段，保持与普通车牌号码一致。
     * 例如：
     * - WJ京12345 - WJ粤12345
     *
     *
     * 武警总队车牌
     * 车牌号码长度：7 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * W   J  号码 号码 号码 号码 号码
     * 其中号码字段，保持与普通车牌号码一致。
     * 例如：
     * - WJ1234J - WJ95001
     *
     *
     * 普通警察车牌
     * 车牌号码长度：7 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 省份  发证机关   号码 号码 号码 号码 警
     * 其中第7位固定为“警”字，其它位置与普通车牌号码一致；
     *
     *
     * O字车牌
     * 车牌号码长度：7 位
     * 车牌号码格式：
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 省份  O  号码 号码 号码 号码 号码
     * 其中第1位固定为字母“O”，其它位置与普通车牌号码一致。
     * </pre>
     *
     * @param plate
     * @return
     */
    public static boolean isWJPlate(String plate) {
        String wjPattern = "^(WJ[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][1-9]{4}|WJ[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][1-9]{5}|WJ[1-9]{5}|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{4}[警]|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][O][\\dABCDEFGHJKLNMxPQRSTUVWXYZ]{5})$";
        return plate.matches(wjPattern);
    }

    /**
     * 军用车牌2012式
     * <pre>
     * 车牌号码长度：7 位
     *
     * 车牌号码格式：
     *
     * 第1位 第2位    第3位    第4位    第5位    第6位    第7位
     * 军区军种代码  单位代码   号码 号码 号码 号码 号码
     * 军区代码：
     *
     * QVKHBSLJNGCEZ
     *
     * 代表各大军区、总部、军种：
     *
     * Q 战区首字母（新式）
     * VKHBSLJNGCEZ 旧式军区车牌前缀。后期根据军队车牌情况可能只保存“Q”字母。
     * 单位代码：
     *
     * 与普通民用车牌发证机关代码的字母一致
     * </pre>
     *
     * @param plate
     * @return
     */
    public static boolean isMilitaryVehiclePlate(String plate) {
        //V字头序列(军委、四总部、军直单位)
        //K字头序列(空军)
        //H字头序列(海军)
        //B字头序列(北京军区)
        //N字头序列(南京军区)
        //G字头序列(广州军区)
        //S字头序列(沈阳军区)
        //C字头序列(成都军区)
        //L字头序列(兰州军区)
        //J字头序列(济南军区)
        String mvPattern = "^(V[ABCDEFGRTVKMO][·]{0,1}[0-9]{5}|K[ABCDOREFKUHGJM][·]{0,1}[0-9]{5}|H[ABCDEFGLOR][·]{0,1}[0-9]{5}|B[ABCDKMNORVY][·]{0,1}[0-9]{5}|N[ABCDKMNORVY][·]{0,1}[0-9]{5}|G[ABCDKJMNORVY][·]{0,1}[0-9]{5}|S[ABCDKMNORVY][·]{0,1}[0-9]{5}|C[ABCDKMNORVY][·]{0,1}[0-9]{5}|L[ABCDKMNORVY][·]{0,1}[0-9]{5}|J[ABCDKMNORVY][·]{0,1}[0-9]{5})$";
        return plate.matches(mvPattern);
    }
    /**
     * 获取深色外的随机颜色
     *
     * @return
     */
    public static int getRandomColor() {
        return 0xff000000 | new Random().nextInt(0x00ffffff);
    }


    public static int dip2px(Context context, float dipValue) {
        if (context == null) {
            return (int) dipValue;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    /**
     * 大陆号码或香港号码均可
     */
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String phone) throws PatternSyntaxException {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    /**
     * 香港手机号码8位数，5|6|8|9开头+7位任意数
     */
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 加密
     *
     * @param datasource byte[]
     * @param password   String
     * @return byte[]
     */
    public static byte[] encrypt(byte[] datasource, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(datasource);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param src      byte[]
     * @param password String
     * @return byte[]
     */
    public static byte[] decrypt(byte[] src, String password) throws Exception {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        return cipher.doFinal(src);
    }


    /**
     * 限制只能输入小数点后两位
     *
     * @param editText
     * @param s
     */
    public static void InputTwo(EditText editText, CharSequence s) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                editText.setText(s);
                editText.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            editText.setText(s);
            editText.setSelection(2);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                editText.setText(s.subSequence(0, 1));
                editText.setSelection(1);
                return;
            }
        }
    }


    public static String getDecimalFormat(double num) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(num);
    }

    public static String getDecimalFormat(float num) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(num);
    }


    public static String getMonthOfDate() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date theDate = calendar.getTime();
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        return sf.format(gcLast.getTime());
    }


    public static String getMon() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = format.format(m);
        return mon;
    }


    private static void dealPattern(int color, SpannableString spannableString, Pattern patten, int start) throws Exception {
        Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            // 返回第一个字符的索引的文本匹配整个正则表达式,ture 则继续递归
            if (matcher.start() < start) {
                continue;
            }
            // 计算该内容的长度，也就是要替换的字符串的长度
            int end = matcher.start() + key.length();
            //设置前景色span
            spannableString.setSpan(new ForegroundColorSpan(color), matcher.start(), end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (end < spannableString.length()) {
                // 如果整个字符串还未验证完，则继续。。
                dealPattern(color, spannableString, patten, end);
            }
            break;
        }
    }

    public static String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    /**
     * 关键字变色
     *
     * @param color
     * @param str
     * @param patterStr
     * @return
     */
    public static SpannableString getKeyWordSpan(int color, String str, String patterStr) {
        SpannableString spannableString = new SpannableString(str);
        try {
            Pattern patten = Pattern.compile(patterStr, Pattern.CASE_INSENSITIVE);
            dealPattern(color, spannableString, patten, 0);
            return spannableString;
        } catch (Exception e) {
            return spannableString;
        }
    }


    /**
     * 弹出Toast
     *
     * @param msg
     */
    public static void showToast(String msg) {
        Toast.makeText(Utils.getContext(), msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 发送消息
     *
     * @param code
     * @param data
     */
    public static void sendMsg(int code, Object data) {
        ZMessageEvent instance = new ZMessageEvent();
        instance.data = data;
        instance.code = code;
        EventBus.getDefault().post(instance);
    }

    /**
     * 发送消息
     *
     * @param code
     * @param data
     */
    public static void sendMsg(int code) {
        EventBus.getDefault().post(code);
    }


    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hide(Activity activity) {
        if (activity.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     *
     * @param activity
     */
    public static void show(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    /**
     * 把十六进制Unicode编码字符串转换为中文字符串
     *
     * @param str
     * @return
     */
    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{2,4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }


    public static String getConstellation(int month, int day) {
        String constellation = "白羊座";
        switch (month) {
            case 1:
                if (day < 22) constellation = "摩羯座";
                else constellation = "水瓶座";
                break;
            case 2:
                if (day < 22) constellation = "水瓶座";
                else constellation = "双鱼座";
                break;
            case 3:
                if (day < 22) constellation = "双鱼座";
                else constellation = "白羊座";
                break;
            case 4:
                if (day < 22) constellation = "白羊座";
                else constellation = "金牛座";
                break;
            case 5:
                if (day < 22) constellation = "金牛座";
                else constellation = "双子座";
                break;
            case 6:
                if (day < 22) constellation = "双子座";
                else constellation = "巨蟹座";
                break;
            case 7:
                if (day < 22) constellation = "巨蟹座";
                else constellation = "狮子座";
                break;
            case 8:
                if (day < 22) constellation = "狮子座";
                else constellation = "处女座";
                break;
            case 9:
                if (day < 22) constellation = "处女座";
                else constellation = "天枰座";
                break;
            case 10:
                if (day < 22) constellation = "天枰座";
                else constellation = "天蝎座";
                break;
            case 11:
                if (day < 22) constellation = "天蝎座";
                else constellation = "射手座";
                break;
            case 12:
                if (day < 22) constellation = "射手座";
                else constellation = "摩羯座";
                break;
        }
        return constellation;
    }


    public static boolean slideHide(int dy, boolean isFirst, View view, int s) {
        if (dy != 0 && Math.abs(dy) > 5) {
            if (dy > 0 && Math.abs(dy) >= 20) {
                if (isFirst && s == 2) {
                    view.animate().translationY(view.getHeight() * 2);
                    isFirst = !isFirst;
                }
                return isFirst;
            } else {
                view.setVisibility(View.VISIBLE);
                if (Math.abs(dy) >= 20)
                    if (!isFirst && s == 2) {
                        view.animate().translationY(0);
                        isFirst = !isFirst;
                    }
            }
            return isFirst;
        }
        return isFirst;
    }

    public static void isChartPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        } else {
            System.out.println("存在删除");
            String[] tempList = file.list();
            File temp;
            for (int i = 0; i < tempList.length; i++) {
                if (dirPath.endsWith(File.separator)) {
                    temp = new File(dirPath + tempList[i]);
                } else {
                    temp = new File(dirPath + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
            }
        }
    }

    /**
     * @param bmp     获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public static void saveBmp2Gallery(Bitmap bmp, String picName) {

        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;

        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            }

        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //通知相册更新
        MediaStore.Images.Media.insertImage(Utils.getContext().getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        Utils.getContext().sendBroadcast(intent);
        Utils.showToast("保存成功!");
    }


    public static String getVersions() {
        PackageManager manager = Utils.getContext().getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(Utils.getContext().getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }


    public static Date parse(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }

    //由出生日期获得年龄
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }


    public static String getName() {
        Random random = new Random();
        String[] Surname = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
                "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
                "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷",
                "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和",
                "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒",
                "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季"};
        String girl = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽 ";
        String boy = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
        int index = random.nextInt(Surname.length - 1);
        String name = Surname[index]; //获得一个随机的姓氏
        int i = random.nextInt(3);//可以根据这个数设置产生的男女比例
        if (i == 2) {
            int j = random.nextInt(girl.length() - 2);
            if (j % 2 == 0) {
                // name = "女-" + name + girl.substring(j, j + 2);
                name = name + girl.substring(j, j + 2);
            } else {
                name = name + girl.substring(j, j + 1);
            }

        } else {
            int j = random.nextInt(girl.length() - 2);
            if (j % 2 == 0) {
                // name = "男-" + name + boy.substring(j, j + 2);
                name = name + boy.substring(j, j + 2);
            } else {
                name = name + boy.substring(j, j + 1);
            }

        }

        return name;
    }


    public static Bitmap getVideoThumb(String path, int radius) {
        Bitmap bitmap = null;
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        bitmap = media.getFrameAtTime();
        Bitmap blurBitmap = doBlur(bitmap, radius, false);
        bitmap.recycle();
        return blurBitmap;
    }

    public static Bitmap getBlur(Bitmap bitmap) {
        Bitmap blurBitmap = doBlur(bitmap, 10, false);
        bitmap.recycle();
        return blurBitmap;
    }

    public static Bitmap getThumbFrame(String path) {
        Bitmap bitmap = null;
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        bitmap = media.getFrameAtTime();
        return bitmap;
    }

    public static Bitmap getThumbLocalFrame(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);// videoPath 本地视频的路径
        Bitmap bitmap = media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        return bitmap;
    }


    private static String getSortkey(String sortKeyString) {
        String key = sortKeyString.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]")) {
            return key;
        } else
            return "#";
    }


    public static View showPop(Activity activity, int layoutRes) {
        View pop_special = View.inflate(Utils.getContext(), layoutRes, null);
        mPopupWindow = new PopupWindow(pop_special, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        setBackgroundAlpha(0.5f, activity);
        mPopupWindow.setOnDismissListener(() -> setBackgroundAlpha(1.0f, activity));
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        return pop_special;
    }

    public static void setBackgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    public static String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        if (returnValue > 1)
            return (returnValue + "MB");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return (returnValue + "KB");
    }


    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
            Bitmap blurBitmap = doBlur(bitmap, 10, false);
            bitmap.recycle();
            return blurBitmap;
        } catch (IllegalArgumentException e) {
            System.out.println("出错");
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }


    public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

        Bitmap bitmap;
        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

//        print("虚化后 ",bitmap);
        return (bitmap);
    }


    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }


    public static String rvZeroAndDot(String s) {
        if (s.isEmpty()) {
            return null;
        }
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }


    public static double getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius, int outWidth, int outHeight) {
        // 将缩小后的图片做为预渲染的图片
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, outWidth, outHeight, false);
        // 创建一张渲染后的输出图片
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
        // 创建RenderScript内核对象
        RenderScript rs = RenderScript.create(context);
        // 创建一个模糊效果的RenderScript的工具对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间
        // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        // 设置渲染的模糊程度, 25f是最大模糊度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            blurScript.setRadius(blurRadius);
        }
        // 设置blurScript对象的输入内存
        blurScript.setInput(tmpIn);
        // 将输出数据保存到输出内存中
        blurScript.forEach(tmpOut);
        // 将数据填充到Allocation中
        tmpOut.copyTo(outputBitmap);
        return outputBitmap;
    }


    /**
     * 取得文件大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSizes(File f) throws Exception {
        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s = fis.available();
        } else {
            f.createNewFile();
        }
        return s;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    // 只允许字母、数字和汉字其余的还可以随时添加比如下划线什么的，但是注意引文符号和中文符号区别
    public static String stringFilter(String str) throws PatternSyntaxException {
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static void setEtFilter(EditText et) {
        if (et == null) {
            return;
        }
        //表情过滤器
        InputFilter emojiFilter = (source, start, end, dest, dstart, dend) -> {
            Pattern emoji = Pattern.compile(
                    "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                return "";
            }
            return null;
        };
        //特殊字符过滤器
        InputFilter specialCharFilter = (source, start, end, dest, dstart, dend) -> {
            String regexStr = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
            Pattern pattern = Pattern.compile(regexStr);
            Matcher matcher = pattern.matcher(source.toString());
            if (matcher.matches()) {
                return "";
            } else {
                return null;
            }

        };
        et.setFilters(new InputFilter[]{emojiFilter, specialCharFilter});
    }


    public static String getMobileFormat(String theMobileStr) {
        return theMobileStr.substring(0, 3) + " " + theMobileStr.substring(3, 7) + " " + theMobileStr.substring(7);
    }


    /*
     */
/**
 * 获取Glide造成的缓存大小
 *
 * @return CacheSize
 *//*

    public static String getCacheSize(Context context) {
     */
/*   try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";*//*

    }
*/


    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;

    }


    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }


/*    public static void clearImageDiskCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(() -> Glide.get(context).clearDiskCache()).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 设置提示字体的大小
     *
     * @param editText 你使用的EditText
     */
    public static void setEditTextHintSize(EditText editText) {
        SpannableString ss = new SpannableString("请输入手机号码");
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(20, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


    public static boolean CheckMobilePhoneNum(String phoneNum) {
        String regex = "^(1[3-9]\\d{9}$)";
        if (phoneNum.length() == 11) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNum);
            if (m.matches()) {
                return true;
            }
        }
        return false;
    }


    public static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }


    public static boolean check(String str) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");//括号内为日期格式，y代表年份，M代表年份中的月份（为避免与小时中的分钟数m冲突，此处用M），d代表月份中的天数
        try {
            sd.setLenient(false);//此处指定日期/时间解析是否不严格，在true是不严格，false时为严格
            sd.parse(str);//从给定字符串的开始解析文本，以生成一个日期
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }


    public static boolean checkAdult(Date date) {

        Calendar current = Calendar.getInstance();
        Calendar birthDay = Calendar.getInstance();
        birthDay.setTime(date);
        Integer year = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
        if (year > 18) {
            return true;
        } else if (year < 18) {
            return false;
        }
        // 如果年相等，就比较月份
        Integer month = current.get(Calendar.MONTH) - birthDay.get(Calendar.MONTH);
        if (month > 0) {
            return true;
        } else if (month < 0) {
            return false;
        }
        // 如果月也相等，就比较天
        Integer day = current.get(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH);
        return day >= 0;
    }


    public static String getOnlineTime(String onlineTimeStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(onlineTimeStr);
            Date dateNow = new Date();

            long timeLong = (dateNow.getTime() / 1000 - date.getTime() / 1000);
            if (timeLong <= 60) {
                return "活跃";
            } else if (timeLong > 60 && timeLong < 60 * 60) {
                int minute = (int) (timeLong / 60);

                return minute + "分钟前活跃";
            } else if (timeLong > 60 * 60 && timeLong < 60 * 60 * 24) {
                int hour = (int) (timeLong / (60 * 60));

                return hour + "小时前活跃";
            } else if (timeLong > 60 * 60 * 24 && timeLong < 60 * 60 * 24 * 30) {
                int day = (int) (timeLong / (60 * 60 * 24));

                return day + "天前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 && timeLong < 60 * 60 * 24 * 30 * 12) {
                int month = (int) (timeLong / (60 * 60 * 24 * 30));

                return month + "个月前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 * 12) {
                int year = (int) (timeLong / (60 * 60 * 24 * 30 * 12));

                return year + "年前活跃";
            } else {
                return onlineTimeStr;
            }

        } catch (ParseException e) {
            e.printStackTrace();

            return onlineTimeStr;

        }


    }

    public static String get2OnlineTime(String onlineTimeStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(onlineTimeStr);
            Date dateNow = new Date();

            long timeLong = (dateNow.getTime() / 1000 - date.getTime() / 1000);
            if (timeLong <= 60) {
                return "活跃";
            } else if (timeLong > 60 && timeLong < 60 * 60) {
                int minute = (int) (timeLong / 60);

                return minute + "分钟前活跃";
            } else if (timeLong > 60 * 60 && timeLong < 60 * 60 * 24) {
                int hour = (int) (timeLong / (60 * 60));

                return hour + "小时前活跃";
            } else if (timeLong > 60 * 60 * 24 && timeLong < 60 * 60 * 24 * 30) {
                int day = (int) (timeLong / (60 * 60 * 24));

                return day + "天前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 && timeLong < 60 * 60 * 24 * 30 * 12) {
                int month = (int) (timeLong / (60 * 60 * 24 * 30));

                return month + "个月前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 * 12) {
                int year = (int) (timeLong / (60 * 60 * 24 * 30 * 12));

                return year + "年前活跃";
            } else {
                return onlineTimeStr;
            }

        } catch (ParseException e) {
            e.printStackTrace();

            return onlineTimeStr;

        }


    }


    /**
     * 格式化时间
     *
     * @param time
     * @return
     */
    public static String formatDateTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (time == null || "".equals(time)) {
            return "";
        }
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar current = Calendar.getInstance();

        Calendar today = Calendar.getInstance();    //今天

        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        Calendar yesterday = Calendar.getInstance();    //昨天
        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 2);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);
        current.setTime(date);
        if (current.after(today)) {
            return "今天";
        } else if (current.before(today) && current.after(yesterday)) {
            return "昨天";
        } else {
            return time;
        }
    }


    public static Date getDate(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTime;
    }

    // 当前时间7天后的时间
    public static String getTimeDay(String time) {
        Date date = getDate(time);
        String lastModified = new SimpleDateFormat("yyyy-MM-dd").format(new Date((date.getTime() + (long) 7 * 24 * 60 * 60 * 1000)));
        return lastModified;
    }

    // 当前时间2天后的时间
    public static String getTime2Day(Long time) {
        String lastModified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((time + (long) 2 * 24 * 60 * 60 * 1000)));
        return lastModified;
    }

    // 当前时间1天后的时间
    public static String getTime1Day(Long time) {
        String lastModified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((time + (long) 1 * 24 * 60 * 60 * 1000)));
        return lastModified;
    }


    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            //同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    //闰年
                    timeDistance += 366;
                } else {
                    //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            //不同年
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }


    public static void input(CharSequence s, EditText et_num, double minNum, String minTip) {
        if (s.toString().contains(".")) {
            if (s.length() == 1) {
                et_num.setText("");
                return;
            }
            if (s.length() - 1 - s.toString().indexOf(".") > 3) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 4);
                et_num.setText(s);
                et_num.setSelection(s.length());
            }
        } else {
            if (s.length() > 6) {
                et_num.setText(s.subSequence(0, 6));
                et_num.setSelection(s.length() - 1);
            }
        }
        if (s.toString().trim().equals(".")) {
            s = "0" + s;
            et_num.setText(s);
            et_num.setSelection(3);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().startsWith(".", 1)) {
                et_num.setText(s.subSequence(0, 1));
                et_num.setSelection(1);
                return;
            }
        }
        try {
            if (Double.parseDouble(s.toString()) < minNum) {
                MToast.showToast(Utils.getContext(), minTip);
                et_num.setText(minNum + "");
                et_num.setSelection(et_num.getText().toString().length());
                return;
            } else {

            }
        } catch (Exception e) {

        }
    }

    public static void input2(CharSequence s, EditText et_num, double minNum, String minTip) {
        if (s.toString().contains(".")) {
            if (s.length() == 1) {
                et_num.setText("");
                return;
            }
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                et_num.setText(s);
                et_num.setSelection(s.length());
            }
        } else {
            if (s.length() > 16) {
                et_num.setText(s.subSequence(0, 16));
                et_num.setSelection(s.length() - 1);
            }
        }
        if (s.toString().trim().equals(".")) {
            s = "0" + s;
            et_num.setText(s);
            et_num.setSelection(2);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().startsWith(".", 1)) {
                et_num.setText(s.subSequence(0, 1));
                et_num.setSelection(1);
                return;
            }
        }
        try {
            if (Double.parseDouble(s.toString()) < minNum) {
                MToast.showToast(Utils.getContext(), minTip);
                et_num.setText(minNum + "");
                et_num.setSelection(et_num.getText().toString().length());
                return;
            } else {

            }
        } catch (Exception e) {

        }
    }


    public static boolean isEmpty(String s) {
        if (s == null || TextUtils.isEmpty(s)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 设置状态栏是否为浅色模式
     *
     * @param activity
     * @param isLightMode
     */
    public static void setStatusBarLightMode(Activity activity,
                                             final boolean isLightMode) {
        setStatusBarLightMode(activity.getWindow(), isLightMode);
    }

    public static void setStatusBarLightMode(Window window,
                                             final boolean isLightMode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = window.getDecorView();
            int vis = decorView.getSystemUiVisibility();
            if (isLightMode) {
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    // 判断为null并拦截
    public static void showTipToastReturn(String keyStr, String tipStr) {
        if (Utils.isEmpty(keyStr)) {
            Utils.showToast(tipStr);
            return;
        }
    }

    /**
     * 返回"" 禁止输入
     * 返回null 不限制输入
     */
    public static void getInputFilter(EditText editText, int digits) {
        editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        // 控制输入框的小数位和长度,这里长度暂时设置为10
        editText.setFilters(new InputFilter[]{new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                // 删除等特殊字符，直接返回
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = dest.toString();
                if (TextUtils.isEmpty(dValue) && source.toString().equals(".")) {
                    return "0.";
                }
                Matcher m = Pattern.compile("[0-9]*").matcher(source);   //除数字外的其他的
                if (dValue.contains(".")) {
                    //已经存在小数点的情况下，只能输入数字
                    if (!m.matches()) {
                        return "";
                    }
                } else {
                    //未输入小数点的情况下，可以输入小数点和数字
                    if (!m.matches() && !source.equals(".")) {
                        return "";
                    }
                }
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];
                    int diff = dotValue.length() + 1 - digits;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                }
                return null;
            }
        }});
    }


    // 获取当天的结束时间
    public static long getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime().getTime();
    }

    // 获取本周的开始时间
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }

    // 获取某个日期的开始时间
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d)
            calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),

                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }


    // 获取本年的开始时间
    public static Date getBeginDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);
        return getDayStartTime(cal.getTime());
    }

    // 获取今年是哪一年
    public static Integer getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return Integer.valueOf(gc.get(1));
    }

    // 获取本月的开始时间
    public static Date getBeginDayOfMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(getNowYear(), getNowMonth() - 1, 1);
        return getDayStartTime(cal.getTime());
    }

    // 获取本月是哪一月
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(2) + 1;
    }

/*    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }*/

    /**
     * @param type   0 天,1 周, 2 月 3年
     * @param number
     * @return
     */
    public static String getStartAndEndTime(int type, int number, String tip) {
        Date dNow = new Date();   //当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        String defaultEndDate = sdf.format(dNow);
        if (number == 0) {
            startTime = type == 0 ? getStartTime() : type == 1 ? getBeginDayOfWeek() : type == 2 ? getBeginDayOfMonth() : getBeginDayOfYear();
        } else {
            Date dBefore = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dNow);
            calendar.add(type == 0 ? Calendar.HOUR_OF_DAY : type == 1 ? Calendar.DAY_OF_WEEK : type == 2 ? Calendar.MONTH : Calendar.YEAR, -number);
            dBefore = calendar.getTime();
            startTime = dBefore;
        }
        System.out.println(tip + "-开始时间:" + sdf.format(startTime) + "-结束时间:" + defaultEndDate);
        return startTime.getTime() + "-" + dNow.getTime();
    }

    /**
     * @param type   0 天,1 周, 2 月 3年
     * @param number
     * @return
     */
    public static String getStartAndEndTimeYMD(int type, int number, String tip) {
        Date dNow = new Date();   //当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date startTime = null;
        String defaultEndDate = sdf.format(dNow);
        if (number == 0) {
            startTime = type == 0 ? getStartTime() : type == 1 ? getBeginDayOfWeek() : type == 2 ? getBeginDayOfMonth() : getBeginDayOfYear();
        } else {
            Date dBefore = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dNow);
            calendar.add(type == 0 ? Calendar.HOUR_OF_DAY : type == 1 ? Calendar.DAY_OF_WEEK : type == 2 ? Calendar.MONTH : Calendar.YEAR, -number);
            dBefore = calendar.getTime();
            startTime = dBefore;
        }
        System.out.println(tip + "-开始时间:" + sdf.format(startTime) + "-结束时间:" + defaultEndDate);
        return sdf.format(startTime) + "-" + defaultEndDate;
    }

    private static Date getStartTime() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date time = cal.getTime();
        return time;
    }

    public static void setBeans(List<Bean> beans, String[] datas) {
        if (beans == null) {
            Utils.showToast("请先实例化集合");
            return;
        }
        for (String s : datas) {
            beans.add(new Bean(s));
        }
    }

    public static List<Bean> setDatas(String[] datas) {
        List<Bean> lists = new ArrayList<>();
        for (String s : datas) {
            lists.add(new Bean(s));
        }
        return lists;
    }

    /**
     * 校验身份证号格式是否正确
     *
     * @param text
     * @return
     */

    public static boolean personIdValidation(String text) {
        String regx = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex);
    }

    /**
     * 匹配Luhn算法：可用于检测银行卡卡号
     *
     * @param cardNo
     * @return
     */

    public static boolean cardValidation(String cardNo) {
        int[] cardNoArr = new int[cardNo.length()];
        for (int i = 0; i < cardNo.length(); i++) {
            cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i)));
        }
        for (int i = cardNoArr.length - 2; i >= 0; i -= 2) {
            cardNoArr[i] <<= 1;
            cardNoArr[i] = cardNoArr[i] / 10 + cardNoArr[i] % 10;
        }
        int sum = 0;
        for (int i = 0; i < cardNoArr.length; i++) {
            sum += cardNoArr[i];
        }
        return sum % 10 == 0;
    }


    public static boolean idCardValidate(String idCard) {
        String[] valCodeArr = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"};
        String[] wi = {"7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"};
        String ai = "";
        String ai1 = "";
        String ai2 = "";

        // 号码的长度 15位或18位
        if (idCard.length() != 15 && idCard.length() != 18) {
            return false;
        }

        // 数字 除最后以为都为数字
        if (idCard.length() == 18) {
            ai = idCard.substring(0, 17);
        } else if (idCard.length() == 15) {
            ai = idCard.substring(0, 6) + "19" + idCard.substring(6, 15);
        }
        if (!isNumeric(ai)) {
            return false;
        }

        // 出生年月是否有效
        String strYear = ai.substring(6, 10); // 年份
        String strMonth = ai.substring(10, 12); // 月份
        String strDay = ai.substring(12, 14); // 月份
        if (!isDataFormat(strYear + "-" + strMonth + "-" + strDay)) {
            return false;
        }

        GregorianCalendar gc = new GregorianCalendar();
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
                    || (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
            return false;
        }
        if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
            return false;
        }

        // 地区码是否有效
        Hashtable h = getAreaCode();
        if (h.get(ai.substring(0, 2)) == null) {
            return false;
        }

        // 判断最后一位的值
        int totalmulAiWi = 0;
        for (int i = 0; i < 17; i++) {
            totalmulAiWi = totalmulAiWi + Integer.parseInt(String.valueOf(ai.charAt(i))) * Integer.parseInt(wi[i]);
        }
        int modValue = totalmulAiWi % 11;
        String strVerifyCode = valCodeArr[modValue];
        ai1 = ai + strVerifyCode.toUpperCase();
        ai2 = ai + strVerifyCode.toLowerCase();
        if (idCard.length() == 18) {
            if (!ai1.equals(idCard) && !ai2.equals(idCard)) {
                return false;
            }
        }

        return true;
    }

    private static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        }

        return false;
    }

    private static boolean isDataFormat(String str) {
        boolean flag = false;
        String regxStr = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
        Pattern pattern1 = Pattern.compile(regxStr);
        Matcher isNo = pattern1.matcher(str);
        if (isNo.matches()) {
            flag = true;
        }
        return flag;
    }

    private static Hashtable getAreaCode() {
        Hashtable hashtable = new Hashtable();
        hashtable.put("11", "北京");
        hashtable.put("12", "天津");
        hashtable.put("13", "河北");
        hashtable.put("14", "山西");
        hashtable.put("15", "内蒙古");
        hashtable.put("21", "辽宁");
        hashtable.put("22", "吉林");
        hashtable.put("23", "黑龙江");
        hashtable.put("31", "上海");
        hashtable.put("32", "江苏");
        hashtable.put("33", "浙江");
        hashtable.put("34", "安徽");
        hashtable.put("35", "福建");
        hashtable.put("36", "江西");
        hashtable.put("37", "山东");
        hashtable.put("41", "河南");
        hashtable.put("42", "湖北");
        hashtable.put("43", "湖南");
        hashtable.put("44", "广东");
        hashtable.put("45", "广西");
        hashtable.put("46", "海南");
        hashtable.put("50", "重庆");
        hashtable.put("51", "四川");
        hashtable.put("52", "贵州");
        hashtable.put("53", "云南");
        hashtable.put("54", "西藏");
        hashtable.put("61", "陕西");
        hashtable.put("62", "甘肃");
        hashtable.put("63", "青海");
        hashtable.put("64", "宁夏");
        hashtable.put("65", "新疆");
        hashtable.put("71", "台湾");
        hashtable.put("81", "香港");
        hashtable.put("82", "澳门");
        hashtable.put("91", "国外");
        return hashtable;
    }


}
